#!/bin/bash
BINUTILS_HOME=$(brew --prefix binutils)
if [ -z ${BINUTILS_HOME} ];then
	brew install binutils
fi
GLIBC_HOME=$(brew --prefix glibc)
if [ -z ${GLIBC_HOME} ];then
	brew install glibc
fi
GCC_HOME=$(brew --prefix gcc)
if [ -z ${GCC_HOME} ];then
	brew install gcc
fi
PKG_CONFIG_PATH=${HOMEBREW_PREFIX}/lib/pkgconfig:${HOMEBREW_PREFIX}/share/pkgconfig:/usr/lib/pkgconfig:/usr/share/pkgconfig
PATH=${BINUTILS_HOME}/bin:${GLIBC_HOME}/bin:${GCC_HOME}/bin:$PATH
GCC_VERSION_MAJOR=$(brew list --versions|grep gcc|awk '{print$2}' | awk -F '.' '{print$1}')
C_INCLUDE_PATH="-I ${GLIBC_HOME}/include -I /usr/include -I /usr/local/include "
CPLUS_INCLUDE_PATH="-I ${GCC_HOME}/include/c++/${GCC_VERSION_MAJOR} -I /usr/local/include "
CC=${GCC_HOME}/bin/gcc-${GCC_VERSION_MAJOR}
CXX=${GCC_HOME}/bin/g++-${GCC_VERSION_MAJOR}
C_FLAGS=" -Wl,-rpath,${GLIBC_HOME}/lib/libc.so.6 "
CXX_FLAGS=" -Wl,-rpath,${GCC_HOME}/lib/gcc/current/libstdc++.so.6 "
LD_FLAGS="-fuse-ld=${BINUTILS_HOME}/bin/gold -L/usr/lib -L/usr/lib64 -L/usr/local/lib -L${GLIBC_HOME}/lib -L${GCC_HOME}/lib/gcc/current"
CMD=""
if [[ "$1" =~ "cmake" ]];then
	CMD="$1 -DCMAKE_C_COMPILER=${CC} -DCMAKE_C_FLAGS=\"${C_FLAGS} ${C_INCLUDE_PATH} -L/usr/lib -L/usr/lib64 -L/usr/local/lib -L${GLIBC_HOME}/lib \" -DCMAKE_CXX_COMPILER=\"${CXX} ${CPLUS_INCLUDE_PATH} -L${GCC_HOME}/lib/gcc/current \" -DCMAKE_CXX_FLAGS=${CXX_FLAGS} $@ "
elif [[ "$1" =~ "configure" ]];then
	CMD="CC=${CC} CXX=${CXX}  CFLAGS=\"${C_FLAGS} ${C_INCLUDE_PATH} -L/usr/lib -L/usr/lib64 -L${GLIBC_HOME}/lib\" CXXFLAGS=\"${CXX_FLAGS} ${CPLUS_INCLUDE_PATH} -L${GCC_HOME}/lib/gcc/current \" LDFLAGS=\"${LD_FLAGS}\" $@ "
else
	echo "un support build tool cmd:$1"
	exit 1
fi
eval $CMD
if [ $? -gt 0 ];then
	echo "run cmd error,cmd:$CMD"
	exit 1
fi
